﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;

namespace CommonLibrary
{
    public static class Functions
    {
        public static byte[] SerializeToBytes<TClass>(TClass message)
        {
            using (var memoryStream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                try
                {
                    formatter.Serialize(memoryStream, message);
                }
                catch
                {
                    return null;
                }
                return memoryStream.ToArray();
            }
        }

        public static T DeserializeFromBytes<T>(byte[] byteMessage)
        {
            using (var streamMessage = new MemoryStream())
            {
                streamMessage.Write(byteMessage, 0, byteMessage.Length);
                streamMessage.Position = 0;
                var formatter = new BinaryFormatter();
                try
                {
                    var messageClass = (T)formatter.Deserialize(streamMessage);
                    return messageClass;
                }
                catch
                {
                    return default(T);
                }
            }
        }

        public static byte[] MessageHash(byte[] bMessage)
        {
            using (SHA1 sha1 = new SHA1CryptoServiceProvider())
            {
                return sha1.ComputeHash(bMessage);
            }
        }

        public static string HashFromBase64StringToBase64String(string base64String)
        {
            return Convert.ToBase64String(MessageHash(Convert.FromBase64String(base64String)));
        }

        public static string HashFromStringToBase64String(string str)
        {
            return Convert.ToBase64String(MessageHash(Encoding.UTF8.GetBytes(str)));
        }
    }
}